import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { RootState } from '@/store';
import { message, Modal, Input } from 'antd';
import './NewHeader.css';

const NewHeader: React.FC = () => {
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();
    const draftId = searchParams.get('draftId');
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [materialPath, setMaterialPath] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);

    // 从 Redux store 中获取当前草稿信息
    const currentDraft = useSelector((state: RootState) => state.drafts.currentDraft);

    // 返回按钮处理函数
    const handleBack = () => {
        navigate('/projects');
    };

    // 保存按钮处理函数
    const handleSave = () => {
        if (!draftId) {
            message.error('未找到草稿ID');
            return;
        }

        // 显示弹窗让用户输入素材路径
        setIsModalVisible(true);
    };

    // 处理弹窗确认
    const handleModalOk = async () => {
        if (!materialPath.trim()) {
            message.warning('请输入素材路径');
            return;
        }

        setIsSubmitting(true);
        try {
            // 使用新的API，将素材路径作为查询参数发送并下载文件
            await downloadDraftWithMaterialPath(materialPath);

            message.success('草稿压缩包下载成功');
            setIsModalVisible(false);
            setMaterialPath('');
        } catch (error) {
            console.error('下载失败:', error);
            message.error(error instanceof Error ? error.message : '下载失败，请重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    // 处理弹窗取消
    const handleModalCancel = () => {
        setIsModalVisible(false);
        setMaterialPath('');
    };

    // 发送素材路径到后端并下载草稿文件
    const downloadDraftWithMaterialPath = async (path: string) => {
        // 根据后端API示例，将material_path作为查询参数
        const url = `/api/draft/script-file/${draftId}/?material_path=${encodeURIComponent(path)}`;

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${localStorage.getItem('token') || ''}`,
                'Content-Type': 'application/json',
            },
        });

        if (!response.ok) {
            throw new Error('下载草稿文件失败');
        }

        // 处理zip文件下载
        const blob = await response.blob();
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = `draft-${draftId}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
    };

    // 获取草稿标题，如果没有草稿或名称为空则显示默认文本
    const draftTitle = currentDraft?.name || '未命名草稿';
    return (
        <div className="new-header-container">
            {/* 左侧返回按钮和Logo */}
            <div className="logo-container">
                <img src="/自由编导-02.png" alt="Logo" className="logo" />
                <button className="back-button" onClick={handleBack}>
                    返回
                </button>
            </div>
            {/* 中间标题 */}
            <div className="title-container">
                <h1 className="draft-title">{draftTitle}</h1>
            </div>

            {/* 右侧保存按钮 */}
            <div className="save-button-container">
                <button className="save-button" onClick={handleSave} disabled={isSubmitting || !draftId}>
                    {isSubmitting ? '保存中...' : '保存'}
                </button>
            </div>

            {/* 素材路径输入弹窗 */}
            <Modal title="设置素材路径" open={isModalVisible} onOk={handleModalOk} onCancel={handleModalCancel} confirmLoading={isSubmitting} okText="确认保存" cancelText="取消" width={500}>
                <div style={{ padding: '20px 0' }}>
                    <p style={{ marginBottom: '16px', color: '#666' }}>请输入本地素材文件夹路径，系统将使用此路径处理素材文件：</p>
                    <Input placeholder="例如：C:\Users\用户名\Desktop\素材文件夹" value={materialPath} onChange={(e) => setMaterialPath(e.target.value)} size="large" disabled={isSubmitting} />
                    <p style={{ marginTop: '8px', fontSize: '12px', color: '#999' }}>请确保路径存在且包含项目所需的素材文件，系统将生成包含草稿和素材的zip压缩包</p>
                </div>
            </Modal>
        </div>
    );
};

export default NewHeader;
